package com.example.fuzzysearch;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.SimpleCursorAdapter;

import com.example.sqlitetest.R;

public class FuzzySearchActivity extends Activity {
	private AutoCompleteTextView account;

	private SimpleCursorAdapter adapter;
	private static Cursor cursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();
		initResourse();
	}

	private void initView() {
		account = (AutoCompleteTextView) findViewById(R.id.account);
		account.addTextChangedListener(new MyTextWatcher());
	}

	private void initResourse() {

	}

	private class MyTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			Log.d("afterTextChanged", s.toString());
			cursor = searchInformation(s.toString());
			int[] to = { R.id.contact_id, R.id.contact_name };
			String[] columns = { ContactsContract.Contacts._ID,
					ContactsContract.Contacts.DISPLAY_NAME };
			adapter = new SimpleCursorAdapter(FuzzySearchActivity.this,
					R.layout.item, cursor, columns, to);
			account.setAdapter(adapter);

		}

		@Override
		public void afterTextChanged(Editable s) {

		}

	}

	private Cursor searchInformation(String args) {
		ContentResolver cr = getContentResolver();
		String[] projection = { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME };
		String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? ";
		String[] selectionArgs = { args + "%" };
		Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, projection,
				selection, selectionArgs, null);
		while (c.moveToNext()) {
			String name = c.getString(c
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			Log.d("search", name);
		}

		return c;
	}

}
